#include "memomodel.h"
#include <QStandardPaths>
#include <QDir>
#include <QFileInfo>

MemoModel::MemoModel(QObject *parent)
    : QAbstractListModel(parent)
{
    qDebug() << "MemoModel构造函数开始";
    if (!initDatabase()) {
        qCritical() << "数据库初始化失败，应用可能无法正常工作";
        // 不抛出异常，但记录错误
    } else {
        qDebug() << "数据库初始化成功";
    }
}

MemoModel::~MemoModel()
{
    if (m_database.isOpen()) {
        m_database.close();
    }
}

int MemoModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    return m_memos.size();
}

QVariant MemoModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() < 0 || index.row() >= m_memos.size()) {
        return QVariant();
    }
    
    const MemoItem &item = m_memos.at(index.row());
    
    switch (role) {
    case IdRole:
        return item.id;
    case TitleRole:
        return item.title;
    case ContentRole:
        return item.content;
    case CreatedAtRole:
        return item.createdAt.toString("yyyy-MM-dd hh:mm:ss");
    case UpdatedAtRole:
        return item.updatedAt.toString("yyyy-MM-dd hh:mm:ss");
    default:
        return QVariant();
    }
}

QHash<int, QByteArray> MemoModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[IdRole] = "memoId";
    roles[TitleRole] = "title";
    roles[ContentRole] = "content";
    roles[CreatedAtRole] = "createdAt";
    roles[UpdatedAtRole] = "updatedAt";
    return roles;
}

bool MemoModel::initDatabase()
{
    if (!connectDatabase()) {
        return false;
    }
    
    // 创建表
    QSqlQuery query(m_database);
    QString createTableSql = R"(
        CREATE TABLE IF NOT EXISTS memos (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            content TEXT NOT NULL,
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL
        )
    )";
    
    if (!query.exec(createTableSql)) {
        qWarning() << "创建表失败:" << query.lastError().text();
        emit errorOccurred("创建数据库表失败: " + query.lastError().text());
        return false;
    }
    
    // 加载已有数据
    loadMemos();
    
    return true;
}

bool MemoModel::connectDatabase()
{
    // 获取应用数据目录
    QString dataPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    qDebug() << "应用数据目录:" << dataPath;
    
    QDir dir;
    if (!dir.exists(dataPath)) {
        if (!dir.mkpath(dataPath)) {
            qCritical() << "创建数据目录失败:" << dataPath;
            emit errorOccurred("创建数据目录失败");
            return false;
        }
        qDebug() << "创建数据目录成功:" << dataPath;
    }
    
    QString dbPath = dataPath + "/memos.db";
    qDebug() << "数据库路径:" << dbPath;
    
    // 检查是否已有连接，先关闭
    if (QSqlDatabase::contains("memo_connection")) {
        QSqlDatabase::removeDatabase("memo_connection");
    }
    
    // 连接SQLite数据库
    m_database = QSqlDatabase::addDatabase("QSQLITE", "memo_connection");
    if (!m_database.isValid()) {
        qCritical() << "SQLite驱动不可用";
        emit errorOccurred("SQLite驱动不可用，请检查Qt SQL模块是否正确安装");
        return false;
    }
    
    m_database.setDatabaseName(dbPath);
    
    if (!m_database.open()) {
        qCritical() << "打开数据库失败:" << m_database.lastError().text();
        emit errorOccurred("打开数据库失败: " + m_database.lastError().text());
        return false;
    }
    
    qDebug() << "数据库连接成功";
    return true;
}

void MemoModel::loadMemos()
{
    beginResetModel();
    m_memos.clear();
    
    QSqlQuery query(m_database);
    QString selectSql = "SELECT id, title, content, created_at, updated_at FROM memos ORDER BY updated_at DESC";
    
    if (!query.exec(selectSql)) {
        qWarning() << "查询失败:" << query.lastError().text();
        emit errorOccurred("查询数据失败: " + query.lastError().text());
        endResetModel();
        return;
    }
    
    while (query.next()) {
        MemoItem item;
        item.id = query.value(0).toInt();
        item.title = query.value(1).toString();
        item.content = query.value(2).toString();
        
        // 解析日期时间，如果失败则使用当前时间
        QString createdAtStr = query.value(3).toString();
        QString updatedAtStr = query.value(4).toString();
        item.createdAt = QDateTime::fromString(createdAtStr, Qt::ISODate);
        item.updatedAt = QDateTime::fromString(updatedAtStr, Qt::ISODate);
        
        if (!item.createdAt.isValid()) {
            item.createdAt = QDateTime::currentDateTime();
        }
        if (!item.updatedAt.isValid()) {
            item.updatedAt = QDateTime::currentDateTime();
        }
        
        m_memos.append(item);
    }
    
    endResetModel();
    emit countChanged();
}

bool MemoModel::addMemo(const QString &title, const QString &content)
{
    if (title.trimmed().isEmpty()) {
        emit errorOccurred("标题不能为空");
        return false;
    }
    
    QDateTime now = QDateTime::currentDateTime();
    QSqlQuery query(m_database);
    
    query.prepare("INSERT INTO memos (title, content, created_at, updated_at) VALUES (?, ?, ?, ?)");
    query.addBindValue(title);
    query.addBindValue(content);
    query.addBindValue(now.toString(Qt::ISODate));
    query.addBindValue(now.toString(Qt::ISODate));
    
    if (!query.exec()) {
        qWarning() << "插入失败:" << query.lastError().text();
        emit errorOccurred("添加备忘录失败: " + query.lastError().text());
        return false;
    }
    
    // 重新加载数据
    loadMemos();
    return true;
}

bool MemoModel::updateMemo(int id, const QString &title, const QString &content)
{
    if (title.trimmed().isEmpty()) {
        emit errorOccurred("标题不能为空");
        return false;
    }
    
    QDateTime now = QDateTime::currentDateTime();
    QSqlQuery query(m_database);
    
    query.prepare("UPDATE memos SET title = ?, content = ?, updated_at = ? WHERE id = ?");
    query.addBindValue(title);
    query.addBindValue(content);
    query.addBindValue(now.toString(Qt::ISODate));
    query.addBindValue(id);
    
    if (!query.exec()) {
        qWarning() << "更新失败:" << query.lastError().text();
        emit errorOccurred("更新备忘录失败: " + query.lastError().text());
        return false;
    }
    
    if (query.numRowsAffected() == 0) {
        emit errorOccurred("未找到要更新的备忘录");
        return false;
    }
    
    // 重新加载数据
    loadMemos();
    return true;
}

bool MemoModel::deleteMemo(int id)
{
    QSqlQuery query(m_database);
    query.prepare("DELETE FROM memos WHERE id = ?");
    query.addBindValue(id);
    
    if (!query.exec()) {
        qWarning() << "删除失败:" << query.lastError().text();
        emit errorOccurred("删除备忘录失败: " + query.lastError().text());
        return false;
    }
    
    if (query.numRowsAffected() == 0) {
        emit errorOccurred("未找到要删除的备忘录");
        return false;
    }
    
    // 重新加载数据
    loadMemos();
    return true;
}

QVariantMap MemoModel::getMemo(int index) const
{
    QVariantMap map;
    
    if (index < 0 || index >= m_memos.size()) {
        return map;
    }
    
    const MemoItem &item = m_memos.at(index);
    map["id"] = item.id;
    map["title"] = item.title;
    map["content"] = item.content;
    map["createdAt"] = item.createdAt.toString("yyyy-MM-dd hh:mm:ss");
    map["updatedAt"] = item.updatedAt.toString("yyyy-MM-dd hh:mm:ss");
    
    return map;
}

